/**
 * File		: Matrix.java
 * Subject	: Represents a 4x4 matrix
 * Author	: Isaac Parenteau (locus2k@gmail.com)
 * Date		: April 25th, 2011
 * Note		: Code borrowed from Google and modified to fit the project 
 * CopYright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * You may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either xXpress or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
package src.project.util;

public class Matrix {
	public float[][] Matrix = new float[4][4];
	
	/**
	 * Default Constructor
	 */
	public Matrix(){}
	
	/**
	 * Constructor
	 * Copies another matrix into a new one
	 * @param other matrix to copy
	 */
	public Matrix(Matrix other){
		for(int i = 0; i < 4; i++)
			for(int j = 0; j < 4; j++)
				Matrix[i][j] = other.Matrix[i][j];
	}
	
	/**
	 * Multiplies two matrixes together
	 * @param source source matrix
	 * @param dest destination matrix
	 */
	public void multiply(Vertex source, Vertex dest){
		dest.X = source.X * Matrix[0][0] + source.Y * Matrix[1][0] + source.Z * Matrix[2][0] + Matrix[3][0];
		dest.Y = source.X * Matrix[0][1] + source.Y * Matrix[1][1] + source.Z * Matrix[2][1] + Matrix[3][1];
		dest.Z = source.X * Matrix[0][2] + source.Y * Matrix[1][2] + source.Z * Matrix[2][2] + Matrix[3][2];
	}
	
	/**
	 * Multiplies the matrix by another matrix
	 * @param other matrix to multiply by
	 * @return the resultant
	 */
	public Matrix multiply(Matrix other){
		Matrix result = new Matrix();
		float[][] matrix1 = this.Matrix;
		float[][] matrix2 = other.Matrix;
		
		for(int i = 0; i < 4; i++)
			for(int j = 0; j < 4; j++)
				result.Matrix[i][j] = 
					matrix1[i][0]*matrix2[0][j] + matrix1[i][1]*matrix2[1][j] + 
					matrix1[i][2]*matrix2[2][j] + matrix1[i][3]*matrix2[3][j];
		
		return result;
	}
	
	/**
	 * Sets the identity matrix
	 */
	public void setIdentity(){
		for(int i = 0; i < 4; i++)
			for(int j = 0; j < 4; j++)
				Matrix[i][j] = (i == j ? 1f : 0f);
	}
	
	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder("[ ");
		for (int i = 0; i < 4; i++) {
			for (int j = 0; j < 4; j++) {
				builder.append(Matrix[i][j]);
				builder.append(" ");
			}
			if (i < 2)
				builder.append("\n  ");
		}
		builder.append(" ]");
		return builder.toString();
	}
}
